import store from '@/store'
import config from '@/admin.config.js'
import {nologin,home} from './nologin'
export function initInterceptor() {
	
	
	uni.addInterceptor('redirectTo', {
	    invoke(params) {
			let realUrl = params.url ? params.url : '' 
			if(params.url.indexOf('?')){
				realUrl = params.url.substring(0,params.url.indexOf('?'))
			}
			
			if(home().includes(realUrl) ){
				store.commit('app/SET_HOME_STATUS',false)
			}else{
				store.commit('app/SET_HOME_STATUS',true)
			}
			
			if(nologin().includes(realUrl)){
				return 'no need login'
			}
			
	        if (!store.getters['user/isTokenValid']) {
	            uni.showModal({
	                content: '登录状态失效，请重新登录',
	                showCancel: false,
	                success() {
	                    uni.reLaunch({
	                        url: config.login.url
	                    })
	                }
	            })
	        }
	    },
	    fail: ({
	        errMsg
	    }) => {
	        if (errMsg.indexOf('is not found') !== -1) { // 404
	            uni.navigateTo({
	                url: config.error.url + '?errMsg=' + errMsg
	            })
	        }
	    }
	})
	
    uni.addInterceptor('navigateTo', {
        invoke(params) {
			let realUrl = params.url ? params.url : '' 
			if(params.url.indexOf('?')){
				realUrl = params.url.substring(0,params.url.indexOf('?'))
			}
			
			if(home().includes(realUrl) ){
				store.commit('app/SET_HOME_STATUS',false)
			}else{
				store.commit('app/SET_HOME_STATUS',true)
			} 
			
			if(nologin().includes(realUrl)){
				return 'no need login'
			}
			console.log('token vail')
            if (store.getters['user/isTokenValid'] === false ) {
                uni.showModal({
                    content: '登录状态失效，请重新登录',
                    showCancel: false,
                    success() {
                        uni.reLaunch({
                            url: config.login.url
                        })
                    }
                })
            }
        },
        fail: ({
            errMsg
        }) => {
            if (errMsg.indexOf('is not found') !== -1) { // 404
                uni.navigateTo({
                    url: config.error.url + '?errMsg=' + errMsg
                })
            }
        }
    })
}
